<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\OrderProduct;
use common\models\CustomerOrder;
use common\models\TransferUndertake;
use common\models\Product;
use common\models\Department;
use common\models\Employees;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class StatisticForm extends Model
{
	public $year;
	public $month;
	public $day;
	public $product;
	public $department;
	public $employee;
	public $type;

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
			[['year', 'month', 'day', 'product', 'department', 'employee', 'type'], 'safe']
		];
	}

	/**
	 * [query 根据特定条件获取统计结果集]
	 * @return [type] [description]
	 */
	public function query()
	{
		$data = OrderProduct::find()->where('id <> 0');
		if ($this->year && !$this->month && !$this->product && !$this->day && !$this->department && !$this->employee) {
			$year = strtotime($this->year.'/1/1');
			$now_year = mktime(0,0,0,1,1,date('Y', $year));
			$next_year = mktime(0,0,0,1,1,date('Y', $year)+1);
			$data = $data->where(['>', 'created_at', $now_year])->andWhere(['<', 'created_at', $next_year]);
			
			return $this->handle($data->all(), $this->type);
		}

		if ($this->year && !$this->month && $this->product && !$this->day && !$this->department && !$this->employee) {
			$year = strtotime($this->year.'/1/1');
			$now_year = mktime(0,0,0,1,1,date('Y', $year));
			$next_year = mktime(0,0,0,1,1,date('Y', $year)+1);
			$data = $data->where(['>', 'created_at', $now_year])->andWhere(['<', 'created_at', $next_year]);
			$data = $data->andWhere(['in', 'pid', $this->product]);
			
			return $this->handle($data->all(), $this->type);
		}

		if ($this->month && !$this->product && !$this->day && !$this->department && !$this->employee) {
			$month = strtotime($this->year.'/'.$this->month.'/1');
			$next_month = strtotime($this->year.'/'.($this->month + 1).'/1');
			if ($this->month == '12') {
				$next_month = strtotime($this->year.'/'.$this->month.'/31');
			}
			$data = $data->where(['>', 'created_at', $month])->andWhere(['<', 'created_at', $next_month]);

			return $this->handleMonth($this->year, $this->month, $data->all(), $this->type);
		}

		if ($this->month && $this->product && !$this->day && !$this->department && !$this->employee) {
			$month = strtotime($this->year.'/'.$this->month.'/1');
			$next_month = strtotime($this->year.'/'.($this->month + 1).'/1');
			if ($this->month == '12') {
				$next_month = strtotime($this->year.'/'.$this->month.'/31');
			}
			$data = $data->where(['>', 'created_at', $month])->andWhere(['<', 'created_at', $next_month]);
			$data = $data->andWhere(['in', 'pid', $this->product]);

			return $this->handleMonth($this->year, $this->month, $data->all(), $this->type);
		}

		if ($this->day && !$this->product && !$this->department && !$this->employee) {
			$day = strtotime($this->year.'/'.$this->month.'/'.$this->day);
			$next_day = strtotime($this->year.'/'.$this->month.'/'.($this->day+1));
			$data = $data->where(['>', 'created_at', $day])->andWhere(['<', 'created_at', $next_day]);

			return $this->handleDay($this->year, $this->month, $this->day, $data->all(), $this->type);
		}

		if ($this->day && $this->product && !$this->department && !$this->employee) {
			$day = strtotime($this->year.'/'.$this->month.'/'.$this->day);
			$next_day = strtotime($this->year.'/'.$this->month.'/'.($this->day+1));
			$data = $data->where(['>', 'created_at', $day])->andWhere(['<', 'created_at', $next_day]);
			$data = $data->andWhere(['in', 'pid', $this->product]);

			return $this->handleDay($this->year, $this->month, $this->day, $data->all(), $this->type);
		}

		if ($this->department && !$this->employee) {
			if ($this->year && !$this->month) {
				$year = strtotime($this->year.'/1/1');
				$now_time = mktime(0,0,0,1,1,date('Y', $year));
				$next_time = mktime(0,0,0,1,1,date('Y', $year)+1);
			}
			if ($this->month && !$this->day) {
				$now_time = strtotime($this->year.'/'.$this->month.'/1');
				$next_time = strtotime($this->year.'/'.($this->month + 1).'/1');
				if ($this->month == '12') {
					$next_time = strtotime($this->year.'/'.$this->month.'/31');
				}
			}
			if ($this->day) {
				$now_time = strtotime($this->year.'/'.$this->month.'/'.$this->day);
				$next_time = strtotime($this->year.'/'.$this->month.'/'.($this->day+1));
			}
			$data = $data->where(['>', 'created_at', $now_time])->andWhere(['<', 'created_at', $next_time]);
			if ($this->product) {
				$data = $data->andWhere(['in', 'pid', $this->product]);
			}
			$did = $this->filterDepartment($this->department);
			$data = $data->andWhere(['in', 'did', $did]);

			return $this->handleDepart($this->department, $data->all(), $this->type);
		}

		if ($this->employee) {
			$data = OrderProduct::find()->where('order_product.id <> 0');
			$data = $data->joinWith('customerorder')->where(['in', 'customer_order.sid', $this->employee]);
			if ($this->year && !$this->month) {
				$year = strtotime($this->year.'/1/1');
				$now_time = mktime(0,0,0,1,1,date('Y', $year));
				$next_time = mktime(0,0,0,1,1,date('Y', $year)+1);
			}
			if ($this->month && !$this->day) {
				$now_time = strtotime($this->year.'/'.$this->month.'/1');
				$next_time = strtotime($this->year.'/'.($this->month + 1).'/1');
				if ($this->month == '12') {
					$next_time = strtotime($this->year.'/'.$this->month.'/31');
				}
			}
			if ($this->day) {
				$now_time = strtotime($this->year.'/'.$this->month.'/'.$this->day);
				$next_time = strtotime($this->year.'/'.$this->month.'/'.($this->day+1));
			}
			$data = $data->andWhere(['>', 'order_product.created_at', $now_time])->andWhere(['<', 'order_product.created_at', $next_time]);
			if ($this->product) {
				$data = $data->andWhere(['in', 'order_product.pid', $this->product]);
			}

			return $this->handleEmployee($this->employee, $data->all(), $this->type);
		}

		return $data;
	}
	/**
	 * [handle 按年份查询]
	 * @param  [type] $data [数据集]
	 * @param  [type] $type [类型]
	 * @return [type]       [description]
	 */
	public function handle($data, $type) {
		$product = Product::find()->asArray()->all();
		if ($this->product) {
			$product = Product::find()->where(['id' => $this->product])->asArray()->all();
		}

		$array = [];
		foreach ($product as $val) {
			$array[$val['name']] = [
				'1' => 0,
				'2' => 0,
				'3' => 0,
				'4' => 0,
				'5' => 0,
				'6' => 0,
				'7' => 0,
				'8' => 0,
				'9' => 0,
				'10' => 0,
				'11' => 0,
				'12' => 0
			];
		}
		if ($type == 'count') {
			foreach ($data as $val) {
				$month = (string)ltrim(date('m', $val->created_at), '0');
				$array[$val->pname][$month] += 1;
			}
		}
		if ($type == 'fee') {
			foreach ($data as $val) {
				$month = (string)ltrim(date('m', $val->created_at), '0');
				$array[$val->pname][$month] += $val->price;
			}
		}

		$a = [];
		$b = [];
		foreach ($array as $key => $val) {
			$a['name'] = $key;
			$a['data'] = $val;
			array_push($b, $a);
		}
		$color = Product::find()->asArray()->all();
		$color = ArrayHelper::map($color, 'name', 'color');
		foreach ($b as $key =>$val) {
			$b[$key]['color'] = $color[$val['name']];
		}

		return $b;
	}

	/**
	 * [handleMonth 按月份查询]
	 * @param  [type] $y    [年]
	 * @param  [type] $m    [月]
	 * @param  [type] $data [数据集]
	 * @param  [type] $type [类型]
	 * @return [type]       [description]
	 */
	public function handleMonth($y, $m, $data, $type) {
		$product = Product::find()->asArray()->all();

		if ($this->product) {
			$product = Product::find()->where(['id' => $this->product])->asArray()->all();
		}
		$d = date('j', mktime(0,0,1,($m==12?1:$m+1),1,($m==12?$y+1:$y))-24*3600);
		$data_arr = [];
		for ($i=1;$i<=$d;$i++) {
			$data_arr[$i] = 0;
		}
		$arr = [];
		foreach ($product as $val) {
			$arr[$val['name']] = $data_arr;
		}
		if (!empty($data)) {
			if ($type == 'count') {
				foreach ($data as $val) {
					$day = ltrim(date('d', $val->created_at), '0');
					$arr[$val->pname][$day] += 1;
				}
			}
			if ($type == 'fee') {
				foreach ($data as $val) {
					$day = ltrim(date('d', $val->created_at), '0');
					$arr[$val->pname][$day] += $val->price;
				}
			}

		}

		$a = [];
		$b = [];
		foreach ($arr as $key => $val) {
			$a['name'] = $key;
			$a['data'] = $val;
			array_push($b, $a);
		}
		$color = Product::find()->asArray()->all();
		$color = ArrayHelper::map($color, 'name', 'color');
		foreach ($b as $key =>$val) {
			$b[$key]['color'] = $color[$val['name']];
		}

		return $b;
	}

	/**
	 * [handleDay 按日查询数据]
	 * @param  [type] $y    [年]
	 * @param  [type] $m    [月]
	 * @param  [type] $d    [日]
	 * @param  [type] $data [数据集]
	 * @param  [type] $type [类型]
	 * @return [type]       [description]
	 */
	public function handleDay($y, $m, $d, $data, $type)
	{
		$product = Product::find()->asArray()->all();
		if ($this->product) {
			$product = Product::find()->where(['id' => $this->product])->asArray()->all();
		}
		$count = ArrayHelper::map($product, 'name', 0);

		$arr = [];
		if ($type == 'count') {
			foreach ($data as $key => $val) {
				$count[$val->pname] += 1;
			}
		}
		if ($type == 'fee') {
			foreach ($data as $key => $val) {
				$count[$val->pname] += $val->price;
			}
		}

		foreach ($product as $key => $val) {
			$arr[$key]['name'] = $val['name'];
			$arr[$key]['data'] = $count[$val['name']];
			$arr[$key]['color'] = '';
		}
		$color = Product::find()->asArray()->all();
		$color = ArrayHelper::map($color, 'name', 'color');
		foreach ($arr as $key =>$val) {
			$arr[$key]['color'] = $color[$val['name']];
			$arr[$key]['data'] = [$d => $val['data']];
		}

		return $arr;
	}

	/**
	 * [handleDepart 部门查询数据]
	 * @param  [type] $department [部门集合]
	 * @param  [type] $data       [部门产品集合]
	 * @return [type]             [description]
	 */
	public function handleDepart($department, $data, $type)
	{
		$result = [];
		$arr = [];
		$product = Product::find()->asArray()->all();
		if ($this->product) {
			$product = Product::find()->where(['id' => $this->product])->asArray()->all();
		}
		$department = Department::find()->where(['in', 'id', $department])->asArray()->all();
		$department = ArrayHelper::map($department, 'name', 0);

		$dname = Department::find()->asArray()->all();
		$dname = ArrayHelper::map($dname, 'id', 'name');

		foreach ($product as $val) {
			$arr[$val['name']] = $department;
		}

		if ($type == 'count') {
			foreach ($data as $val) {
				if (array_key_exists($dname[$val->did], $arr[$val->pname])) {
					$arr[$val->pname][$dname[$val->did]] += 1;
					$pids = $this->parents($val->did);
					foreach ($pids as $pid) {
						if (array_key_exists($dname[$pid], $arr[$val->pname])) {
							$arr[$val->pname][$dname[$pid]] += 1;
						}
					}
				} else {
					$pids = $this->parents($val->did);
					foreach ($pids as $pid) {
						if (array_key_exists($dname[$pid], $arr[$val->pname])) {
							$arr[$val->pname][$dname[$pid]] += 1;
						}
					}
				}
			}
		}

		if ($type == 'fee') {
			foreach ($data as $val) {
				if (array_key_exists($dname[$val->did], $arr[$val->pname])) {
					$arr[$val->pname][$dname[$val->did]] += $val->price;
					$pids = $this->parents($val->did);
					foreach ($pids as $pid) {
						if (array_key_exists($dname[$pid], $arr[$val->pname])) {
							$arr[$val->pname][$dname[$pid]] += $val->price;
						}
					}
				} else {
					$pids = $this->parents($val->did);
					foreach ($pids as $pid) {
						if (array_key_exists($dname[$pid], $arr[$val->pname])) {
							$arr[$val->pname][$dname[$pid]] += $val->price;
						}
					}
				}
			}
		}

		$color = Product::find()->asArray()->all();
		$color = ArrayHelper::map($color, 'name', 'color');		
		foreach ($product as $key => $val) {
			$result[$key]['name'] = $val['name'];
			$result[$key]['color'] = $color[$val['name']];
			$result[$key]['data'] = $arr[$val['name']];
		}

		return $result;
	}

	/**
	 * [parents 得到父部门id集]
	 * @return [type] [list]
	 */
	public function parents($did)
	{
		$arr = [];
		$dep = Department::find()->asArray()->all();

		for ($i=0;$i<count($dep);$i++) {
			if ($this->parentExist($dep[$i]['id'], $did)) {
				array_push($arr, $dep[$i]['id']);
			}
		}

		return $arr;
	}

	public function parentExist($pid, $did)
	{
		$dep = Department::find()->asArray()->all();
		$dep_json = ArrayHelper::map($dep, 'id', 'pid');
		if (array_key_exists($did, $dep_json)) {
			if ($pid == $dep_json[$did]) {

				return true;
			} else {
				if ($this->parentExist($pid, $dep_json[$did])) {

					return true;
				} else {

					return false;
				}
			}
		}

		return false;
	}

	/**
	 * [handleEmployee 员工查询数据]
	 * @param  [type] $data [员工产品集合]
	 * @return [type]       [description]
	 */
	public function handleEmployee($employee, $data, $type)
	{
		$arr = [];
		$product = Product::find()->asArray()->all();
		if ($this->product) {
			$product = Product::find()->where(['id' => $this->product])->asArray()->all();
		}
		$employee = Employees::find()->where(['in', 'id', $employee])->asArray()->all();
		$employee = ArrayHelper::map($employee, 'realname', 0);
		foreach ($product as $val) {
			$arr[$val['name']] = $employee;
		}
		if ($type == 'count') {
			foreach ($data as $val) {
				$employee = Employees::findOne($val->customerorder->sid)->realname;
				$arr[$val->pname][$employee] += 1;
			}
		}
		if ($type == 'fee') {
			foreach ($data as $val) {
				$employee = Employees::findOne($val->customerorder->sid)->realname;
				$arr[$val->pname][$employee] += $val->price;
			}
		}

		$color = Product::find()->asArray()->all();
		$color = ArrayHelper::map($color, 'name', 'color');		
		foreach ($product as $key => $val) {
			$result[$key]['name'] = $val['name'];
			$result[$key]['color'] = $color[$val['name']];
			$result[$key]['data'] = $arr[$val['name']];
		}
		
		return $result;
	}

	/**
	 * [filterDepartment 过滤部门]
	 * @return [type] [description]
	 */
	public function filterDepartment($dids)
	{
		$result = [];
		$department = Department::find()->asArray()->all();
		$department = ArrayHelper::map($department, 'id', 'pid');

		$order_product = OrderProduct::find();
		$order_arr = $order_product->all();
		for ($i=0;$i<$order_product->count();$i++) {
			if (in_array($order_arr[$i]->did, $dids)) {
				array_push($result, $order_arr[$i]);
			} else {
				$exist = $this->getParent($department[$order_arr[$i]->did], $dids);

				if ($exist) {
					array_push($result, $order_arr[$i]);
				} else {
					continue;
				}
			}
		}
		$arr = [];
		if ($result) {
			foreach ($result as $val) {
				array_push($arr, $val->did);
			}
		}

		return $arr?array_unique($arr):$arr;
	}

	public function getParent($did, $dids)
	{
		$parent_dep = Department::findOne($did);

		if ($parent_dep) {

			if (in_array($did, $dids)) {

				return true;
			} else {
				if ($this->getParent($parent_dep->pid, $dids)) {

					return true;
				}
			}
		}

		return false;
	}

}